import Vue from 'vue';
import Router from 'vue-router';
import store from '@/store'; // 引入 Vuex Store

Vue.use(Router);

const routes = [
  { path: '/login', name: 'Login', component: () => import('@/pages/LoginPage.vue') },
  { path: '/register', name: 'Register', component: () => import('@/pages/RegisterPage.vue') },
  {
    path: '/',
    name: 'Home',
    component: () => import('@/pages/HomePage.vue'),
    meta: { requiresAuth: true } 
  },
  {
    path: '/list',
    name: 'List',
    component: () => import('@/pages/ListPage.vue'),
    meta: { requiresAuth: true } 
  },
  {
    path: '/userinfo',
    name: 'UserInfo',
    component: () => import('@/pages/UserInfoPage.vue'),
    meta: { requiresAuth: true } 
  }
];

const router = new Router({
  mode: 'history',
  routes
});
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!store.state.user) {
      next({ name: 'Login' });
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;